package com.example.wangda.smart_home_android_v12;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.chinamobile.iot.onenet.mqtt.MqttClient;
import com.chinamobile.iot.onenet.mqtt.MqttService;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;

import static com.example.wangda.smart_home_android_v12.WifiConnect.SecurityMode.WPA2;

public class MainActivity extends Activity{
    private static final String TAG = "__DEBUG__";
    private Handler handle_time_show;
    private Handler handle_online_device;
    private Handler handle_mosfet_ctrl;
    private Handler handle_keepAlive_send;
    private Handler handle_mqtt_reconnect;
    private Handler handle_enter_door;
    private TextView tv_time_show;
    private ImageButton btn_module_1;
    private ImageButton btn_module_2;
    private ImageButton btn_module_3;
    private ImageButton btn_module_4;
    private static TextView log_text;
    private WifiConnect wifiConnect;
    MqttHandle m_MqttHandle;
    IFlytekTTS iFlytekTTs;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /*保持屏幕常亮*/
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        WifiStateBroadCast wifiStateBroadCast = new WifiStateBroadCast();
        iFlytekTTs = new IFlytekTTS(MainActivity.this);
        iFlytekTTs.tts_init();
        tv_time_show = (TextView) findViewById(R.id.time_text);
        btn_module_1 = (ImageButton) findViewById(R.id.module_1);
        btn_module_2 = (ImageButton) findViewById(R.id.module_2);
        btn_module_3 = (ImageButton) findViewById(R.id.module_3);
        btn_module_4 = (ImageButton) findViewById(R.id.module_4);
        log_text = (TextView)findViewById(R.id.log_text);
        //使TextView可以滚动显示
        log_text.setMovementMethod(new ScrollingMovementMethod());
        Log_out("控件初始化完成..");
        new Thread(new thread_time()).start();
        Log_out("定时器任务启动...");
        Log_out("时钟启动...");
        Log_out("系统初始化完成...");
        wifiConnect = new WifiConnect(this);
        wifiConnect.initWifiConnect();
        m_MqttHandle = new MqttHandle(this);
        //Button Click handle
        btn_module_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log_out("Button 1 click");
            }
        });
        btn_module_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log_out("Button 2 click");
            }
        });
        btn_module_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log_out("Button 3 click");
            }
        });
        btn_module_4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log_out("Button 4 click");
            }
        });

        //Time handle
        handle_time_show = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss  E");
                sDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
                String str = sDateFormat.format(new java.util.Date());
                tv_time_show.setText(str);
            }
        };

        handle_online_device = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(GlobalData.ReadDoorDeviceOnlineSta() != 0) {
                    if(GlobalData.ReadDoorDeviceOnlineSta() == GlobalData.CountDown) {
                        btn_module_1.setImageResource(R.drawable.run_image);
                  //      iFlytekTTs.startSpeaking("门口传感器上线");
                        Log_out("门口传感器上线");
                        Log.d(TAG, "门口传感器上线");
                    }
                    GlobalData.SetDoorDeviceOnlineSta(GlobalData.ReadDoorDeviceOnlineSta() - 1);
                }
                if(GlobalData.ReadDoorDeviceOnlineSta() == 1) {
                    btn_module_1.setImageResource(R.drawable.stop_image);
                    iFlytekTTs.startSpeaking("门口传感器离线，请检查");
                    Log_out("门口传感器离线，请检查");
                    Log.d(TAG, "门口传感器离线");
                }

                if(GlobalData.ReadStairsDeviceOnlineSta() != 0) {
                    if(GlobalData.ReadStairsDeviceOnlineSta() == GlobalData.CountDown){
                        btn_module_2.setImageResource(R.drawable.run_image);
                     //   iFlytekTTs.startSpeaking("楼道传感器上线");
                        Log_out("楼道传感器上线");
                        Log.d(TAG, "楼道传感器上线");
                    }
                    GlobalData.SetStairsDeviceOnlineSta(GlobalData.ReadStairsDeviceOnlineSta() - 1);
                }
                if(GlobalData.ReadStairsDeviceOnlineSta() == 1) {
                    btn_module_2.setImageResource(R.drawable.stop_image);
                    iFlytekTTs.startSpeaking("楼道传感器离线，请检查");
                    Log_out("楼道传感器离线，请检查");
                    Log.d(TAG, "楼道传感器离线");
                }

                if(GlobalData.ReadBedDeviceOnlineSta() != 0) {
                    if(GlobalData.ReadBedDeviceOnlineSta() == GlobalData.CountDown){
                        btn_module_3.setImageResource(R.drawable.run_image);
                      //  iFlytekTTs.startSpeaking("卧室传感器上线");
                        Log_out("卧室传感器上线");
                        Log.d(TAG, "卧室传感器上线");
                    }
                    GlobalData.SetBedDeviceOnlineSta(GlobalData.ReadBedDeviceOnlineSta() - 1);
                }
                if(GlobalData.ReadBedDeviceOnlineSta() == 1) {
                    btn_module_3.setImageResource(R.drawable.stop_image);
                    iFlytekTTs.startSpeaking("卧室传感器离线，请检查");
                    Log_out("卧室传感器离线，请检查");
                    Log.d(TAG, "卧室传感器离线");
                }

                if(GlobalData.ReadBookDeviceOnlineSta() != 0) {
                    if(GlobalData.ReadBookDeviceOnlineSta() == GlobalData.CountDown){
                        btn_module_4.setImageResource(R.drawable.run_image);
                       // iFlytekTTs.startSpeaking("书房传感器上线");
                        Log_out("书房传感器上线");
                        Log.d(TAG, "书房传感器上线");
                    }
                    GlobalData.SetBookDeviceOnlineSta(GlobalData.ReadBookDeviceOnlineSta() - 1);
                }
                if(GlobalData.ReadBookDeviceOnlineSta() == 1) {
                    btn_module_4.setImageResource(R.drawable.stop_image);
                    iFlytekTTs.startSpeaking("书房传感器离线，请检查");
                    Log_out("书房传感器离线，请检查");
                    Log.d(TAG, "书房传感器离线");
                }
            }
        };

        handle_mosfet_ctrl = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if((GlobalData.ReadUpTheStairs() != 0) && (GlobalData.ReadMqttConnectSta() == GlobalData.networkConnect)) {
                    if(GlobalData.ReadUpTheStairs() == GlobalData.StairsLightDelay){
                        m_MqttHandle.UserCtrlStairLight("CM2_OP");
                        Log_out("楼道开灯");
                        Log.d(TAG, "楼道开灯");
                    }
                    GlobalData.SetUpTheStairs(GlobalData.ReadUpTheStairs()-1);
                }
                if(GlobalData.ReadUpTheStairs() == 1){
                    m_MqttHandle.UserCtrlStairLight("CM2_CL");
                    Log_out("楼道关灯");
                    Log.d(TAG, "楼道关灯");
                }
            }
        };
        /*进门事件处理*/
        handle_enter_door = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if((GlobalData.ReadEnterTheDoor() != 0) && (GlobalData.ReadMqttConnectSta() == GlobalData.networkConnect)){
                    if(GlobalData.ReadEnterTheDoor() == GlobalData.EnterTheDoorDelay){
                        iFlytekTTs.localPlayWelcome();
                        m_MqttHandle.UserEnterDoor();
                        Log_out("进门事件响应,启动语音播报");
                    }
                    GlobalData.SetEnterTheDoor(GlobalData.ReadEnterTheDoor()-1);
                }
            }
        };

        /*主机向ONENET发送呼吸包*/
        handle_keepAlive_send = new Handler(){
            @Override
            public void handleMessage(Message msg){
                if(GlobalData.ReadHostKeepAlive() == 0){
                    GlobalData.SetHostKeepAlive(60);
                }else{
                    GlobalData.SetHostKeepAlive(GlobalData.ReadHostKeepAlive()-1);
                }
                if((GlobalData.ReadHostKeepAlive() == 1) && (GlobalData.ReadMqttConnectSta() == GlobalData.networkConnect)){
                    m_MqttHandle.UserKeepAlive();
                    Log_out("向ONENET主机发送呼吸包");
                }
                /*如果MQTT没有连接，反复连接服务器*/
                if((GlobalData.ReadMqttConnectSta() != GlobalData.networkConnect) && (GlobalData.ReadHostKeepAlive() == 1))
                {
                    wifiConnect.initWifiConnect();
                    m_MqttHandle.UserConnect();
                    Log_out("MQTT没有连接服务器，正在重试...");
                }
            }
        };

        //MQTT重连
        handle_mqtt_reconnect = new Handler() {
            @Override
            public void handleMessage(Message msg) {
//                    m_MqttHandle.UserConnect();
//                Intent intent = new Intent(MainActivity.this, MqttService.class);
//                startService(intent);
            }
        };
}


    //class handle
    class thread_time implements Runnable{
        //延时连接MQTT
        int loop_count=0;
        @Override
        public void run(){
            while(true){
                try{
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = 12;
                    handle_time_show.sendMessage(msg);
                    handle_online_device.sendEmptyMessage(0);
                    handle_mosfet_ctrl.sendEmptyMessage(0);
                    handle_keepAlive_send.sendEmptyMessage(0);
                    handle_enter_door.sendEmptyMessage(0);
                    if(GlobalData.ReadWifiConnectSta() == WifiStateBroadCast.oneConnect && (loop_count++>60))
                    {
                        loop_count=0;
                        handle_mqtt_reconnect.sendEmptyMessage(0);
                        GlobalData.SetWifiConnectSta(WifiStateBroadCast.connect);
                    }
                }catch(Exception e){
                    Log.d(TAG, "catch = " + e);
                }
            }
        }
    }

    /*作者：王达
    * 时间 2017-10-18
    * 函数功能：Log，输出，可以定向为调试器输出，或者设备端显示输出
    * 参数：str:要打印的字符串 返回：无
    * */
    //Log输出到PC端标志
    public static void Log_out(String str)
    {
        final int _LOG_OUT_PC_ = 0;
        /*数据缓存量-大于该值，会清理部分数据*/
        final int data_buf_size = 400;
        if(_LOG_OUT_PC_ == 1)
        {
            Log.d(TAG, str);
        }else{
            Calendar cal = Calendar.getInstance();
            cal.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            int hour = cal.get(Calendar.HOUR_OF_DAY);
            int min = cal.get(Calendar.MINUTE);
            int sec = cal.get(Calendar.SECOND);

            log_text.append("---" + hour + ":" + min + ":" + sec + ": " + str + '\n');
            if(log_text.getLineCount() == 50)
            {
                String old_string;
                String new_string;
                old_string = log_text.getText().toString();
                new_string = old_string.substring(old_string.length()-data_buf_size);
                log_text.setText(new_string);
            }
            int offset=log_text.getLineCount()*log_text.getLineHeight();
            if (offset > log_text.getHeight()) {
                log_text.scrollTo(0,offset - log_text.getHeight());
            }
        }
    }
}
